﻿using System;
using System.Linq;
using System.ComponentModel;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.Controls;
using System.Collections.Generic;
using QuanLyTiemThuocTay.cls;
using System.Windows.Forms;

namespace QuanLyTiemThuocTay.GiaoDien
{
    public partial class frmNhaCungCap : DevExpress.XtraEditors.XtraForm
    {
        QLTTDataContext db = new QLTTDataContext();
        private int maloi;
        private List<NHACUNGCAPCHECK> ListNCCCHECK = new List<NHACUNGCAPCHECK>();
        private string ma = "";
        public frmNhaCungCap()
        {
            InitializeComponent();
        }

        private void btDong_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Close();
        }

        private void frmNhaCungCap_Load(object sender, EventArgs e)
        {
            btMoi.Enabled = btXoa.Enabled = btSua.Enabled = true;
            btLuu.Enabled = false;
            colTenNhaCC.OptionsColumn.ReadOnly = colDiaChi.OptionsColumn.ReadOnly = true;
            LoadData();
        }

        private void LoadData()
        {
            NHACUNGCAPCHECK ncccheck;
            ListNCCCHECK = new List<NHACUNGCAPCHECK>();
            foreach (var item in db.NHACUNGCAPs.ToList())
            {
                ncccheck = new NHACUNGCAPCHECK();
                ncccheck.CHECK = false;
                ncccheck.MaNhaCC = item.MaNhaCC;
                ncccheck.TenNhaCC = item.TenNhaCC;
                ListNCCCHECK.Add(ncccheck);
            }
            gc.DataSource = new BindingList<NHACUNGCAPCHECK>(ListNCCCHECK);
            gv.RefreshData();
        }

        private void btMoi_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gv.AddNewRow();
            gv.FocusedColumn = colTenNhaCC;
            gv.FocusedRowHandle = GridControl.NewItemRowHandle;
            gv.ShowEditor();
            btLuu.Enabled = true;
            btSua.Enabled = btXoa.Enabled = false;
            colTenNhaCC.OptionsColumn.ReadOnly = colDiaChi.OptionsColumn.ReadOnly = false;
        }

        private void gv_InvalidValueException(object sender, DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs e)
        {
            GridView v = sender as GridView;
            if (v.FocusedColumn.FieldName == "TenNhaCC")
            {
                if (maloi == 1)
                {
                    e.ExceptionMode = ExceptionMode.DisplayError;
                    e.ErrorText = "Dữ liệu phải dài hơn 2 ký tự";
                }
                else if (maloi == 2)
                {
                    e.ExceptionMode = ExceptionMode.DisplayError;
                    e.ErrorText = "Dữ liệu đã có trong hệ thống";
                }
            }
        }

        private void gv_ValidatingEditor(object sender, BaseContainerValidateEditorEventArgs e)
        {
            GridView v = sender as GridView;
            if (v.FocusedColumn != colTenNhaCC)
                return;
            else
            {
                if (e.Value == null || e.Value.ToString().Length < 2)
                {
                    maloi = 1;
                    e.Valid = false;
                    return;
                }
                string giatrimoi = e.Value.ToString();
                if (v.FocusedRowHandle == GridControl.NewItemRowHandle)
                {
                    for (int i = 0; i < gv.RowCount - 1; i++)
                    {
                        var a = db.NHACUNGCAPs.FirstOrDefault(x => x.TenNhaCC == giatrimoi);
                        if (a != null)
                        {
                            maloi = 2;
                            e.Valid = false;
                            return;
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < gv.RowCount; i++)
                    {
                        var b = gv.GetRow(i) as NHACUNGCAP;
                        if (giatrimoi == b.TenNhaCC && i != gv.FocusedRowHandle)
                        {
                            maloi = 2;
                            e.Valid = false;
                            return;
                        }
                    }
                }
            }
        }

        private void btLuu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gv.CloseEditor();
            gv.MoveFirst();
            for (int i = 0; i < gv.RowCount; i++)
            {
                var dulieumoi = gv.GetFocusedRow() as NHACUNGCAP;
                if (dulieumoi == null || dulieumoi.TenNhaCC == null)
                {
                    MessageBox.Show("Có lỗi xảy ra: Dữ liệu nhập chưa đúng.", "Kiểm tra thông tin", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                gv.MoveNext();
            }
            gv.MoveFirst();
            for (int i = 0; i < gv.RowCount; i++)
            {
                var dulieumoi = gv.GetFocusedRow() as NHACUNGCAP;
                if (dulieumoi != null)
                {
                    if (dulieumoi.MaNhaCC != ma)
                    {
                        db = new QLTTDataContext();
                        var dulieucu = db.NHACUNGCAPs.SingleOrDefault(x => x.MaNhaCC == dulieumoi.MaNhaCC);
                        if (dulieucu == null)
                        {
                            var ins = new NHACUNGCAP();
                            ins.MaNhaCC = dulieumoi.MaNhaCC;
                            ins.TenNhaCC = dulieumoi.TenNhaCC;
                            ins.DiaChi = dulieumoi.DiaChi;
                            db.NHACUNGCAPs.InsertOnSubmit(ins);
                            db.SubmitChanges();
                            clsHam.HienThi(Text, "Thêm mới thành công: " + ins.TenNhaCC);
                        }
                        else
                            if (dulieumoi.TenNhaCC != dulieucu.TenNhaCC || dulieumoi.DiaChi != dulieucu.DiaChi)
                            {
                                dulieucu.TenNhaCC = dulieumoi.TenNhaCC;
                                dulieucu.DiaChi = dulieumoi.DiaChi;
                                db.SubmitChanges();
                                clsHam.HienThi(Text, "Cập nhật thành công: " + dulieucu.TenNhaCC);
                            }
                    }
                    else
                    {
                        if (dulieumoi.TenNhaCC != null && dulieumoi.TenNhaCC.Length >= 2)
                        {
                            var ins = new NHACUNGCAP();
                            ins.MaNhaCC = dulieumoi.MaNhaCC;
                            ins.TenNhaCC = dulieumoi.TenNhaCC;
                            ins.DiaChi = dulieumoi.DiaChi;
                            db.NHACUNGCAPs.InsertOnSubmit(ins);
                            db.SubmitChanges();
                            clsHam.HienThi(Text, "Thêm mới thành công: " + ins.TenNhaCC);
                        }
                    }
                }
                gv.MoveNext();
            }
            LoadData();
            btMoi.Enabled = btXoa.Enabled = btSua.Enabled = true;
            btLuu.Enabled = false;
            colTenNhaCC.OptionsColumn.ReadOnly = colDiaChi.OptionsColumn.ReadOnly = true;
            gv.MoveLast();
        }

        private void btXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            bool cochonxoa = false;
            gv.CloseEditor();
            for (int i = 0; i < gv.RowCount; i++)
            {
                if ((gv.GetRow(i) as NHACUNGCAPCHECK).CHECK)
                {
                    cochonxoa = true;
                    break;
                }
            }
            if (cochonxoa && MessageBox.Show("Bạn có chắn chắn xóa những mục đã chọn?", "Xác nhận xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                for (int i = 0; i < gv.RowCount; i++)
                {
                    var donghientai = gv.GetRow(i) as NHACUNGCAPCHECK;
                    if (donghientai.CHECK)
                    {
                        var itemxoa = db.NHACUNGCAPs.SingleOrDefault(x => x.MaNhaCC == donghientai.MaNhaCC);
                        if (itemxoa != null)
                        {
                            try
                            {
                                db.NHACUNGCAPs.DeleteOnSubmit(itemxoa);
                                db.SubmitChanges();
                                clsHam.HienThi(Text, "Xóa thành công: " + itemxoa.TenNhaCC);
                            }
                            catch
                            {
                                MessageBox.Show("Có lỗi xảy ra đối với mục: " + itemxoa.TenNhaCC + ". \n Phục hồi thông tin.", "Không thể xóa", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
                LoadData();
            }
        }

        private void btSua_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            colTenNhaCC.OptionsColumn.ReadOnly = colDiaChi.OptionsColumn.ReadOnly = false;
            btMoi.Enabled = btXoa.Enabled = false;
            btLuu.Enabled = true;
        }

        private void btnNap_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            colTenNhaCC.OptionsColumn.ReadOnly = colDiaChi.OptionsColumn.ReadOnly = true;
            btMoi.Enabled = btXoa.Enabled = btSua.Enabled = true;
            btLuu.Enabled = false;
        }

        private void btPhieuTruoc_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!gv.IsFirstRow)
                gv.MovePrev();
        }

        private void btPhieuTiepTheo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!gv.IsLastRow)
                gv.MoveNext();
        }

        private void btTroGiup_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            MessageBox.Show("Chức năng đang xây dựng.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btIn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            colCheck.Visible = false;
            SaveFileDialog sv = new SaveFileDialog();
            sv.Filter = "Excel 97-2003|*.xls";
            sv.Title = "Lưu...";
            sv.ShowDialog();
            if (sv.FileName != "")
            {
                gv.ExportToXls(sv.FileName);
            }
            colCheck.Visible = true;
        }

        private void gv_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            GridView view = sender as GridView;
            if (ma != "")
            {
                int code = Int32.Parse(ma.Substring(3, ma.Length - 3));
                NHACUNGCAP lt = null;
                do
                {
                    code++;
                    if (code < 10)
                        ma = "NCC000" + code;
                    else if (code < 100)
                        ma = "NCC00" + code;
                    else if (code < 1000)
                        ma = "NCC0" + code;
                    else
                        ma = "" + code;
                    lt = db.NHACUNGCAPs.SingleOrDefault(x => x.MaNhaCC == code.ToString());
                } while (lt != null);
                view.SetRowCellValue(e.RowHandle, colMaNhaCC, ma);
            }
            else
            {
                var cuoicung = db.NHACUNGCAPs.ToList().OrderBy(x => x.MaNhaCC).LastOrDefault() as NHACUNGCAP;
                if (cuoicung != null)
                {
                    int code = Int32.Parse(cuoicung.MaNhaCC.Substring(3, 4));
                    NHACUNGCAP lt = null;
                    do
                    {
                        code++;
                        if (code < 10)
                            ma = "NCC000" + code;
                        else if (code < 100)
                            ma = "NCC00" + code;
                        else if (code < 1000)
                            ma = "NCC0" + code;
                        else
                            ma = "" + code;
                        lt = db.NHACUNGCAPs.SingleOrDefault(x => x.MaNhaCC == code.ToString());
                    } while (lt != null);
                    view.SetRowCellValue(e.RowHandle, colMaNhaCC, ma);
                }
                else
                    view.SetRowCellValue(e.RowHandle, colMaNhaCC, "NCC0001");
                gv.FocusedColumn = gv.VisibleColumns[2];
                gv.ShowEditor();
            }
        }
    }
}